package com.shxy.rlzy.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shxy.rlzy.common.lang.Result;
import com.shxy.rlzy.entity.Menu;
import com.shxy.rlzy.entity.RoleMenu;
import com.shxy.rlzy.entity.User;
import com.shxy.rlzy.service.IMenuService;
import com.shxy.rlzy.service.IRoleMenuService;
import com.shxy.rlzy.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tanhao
 * @since 2021-08-16
 */
@RestController
@RequestMapping("/menu")
@Slf4j
public class MenuController extends BaseController {
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IRoleMenuService roleMenuService;

    @GetMapping("/nav")
    public Result getNavsByAdminId() {
        // 获取用户信息
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Menu> menus = menuService.getNavsByUserName(username);
        // 获取用户能访问的菜单
        List<JSONObject> menuTree = convert2Jsons(menus);
        return Result.succ(menuTree);
    }

    /**
     * 菜单信息
     * @param id
     * @return
     */
    @GetMapping("/info/:id")
    public Result info(@PathVariable(name = "id") Long id) {
        return Result.succ(menuService.getById(id));
    }

    /**
     * 获取所有菜单列表
     * @return
     */
    @GetMapping("/list")
    public Result list() {
        // 获取全部菜单并转换成树形结构
        List<Menu> menus = menuService.getMenusAll();
        // 转换成前端需要的数据
        List<JSONObject> list = convert2Jsons(menus);
        return Result.succ(list);
    }

    /**
     * 获取指定角色的菜单列表及可访问列表
     * @return
     */
    @GetMapping("/items/{roleId}")
    public Result items(@PathVariable Long roleId) {
        // 获取所有菜单
        List<Menu> menus = menuService.getMenusAll();
        // 获取角色能访问的菜单编号列表
        List<Long> ids = roleMenuService
                .listByRoleId(roleId)
                .stream().map(RoleMenu::getMenuId)
                .collect(Collectors.toList());

        // 将菜单转换成树形结构
        List<JSONObject> menuTree = convert2Jsons(menus);
        JSONObject result = JSONUtil.createObj();
        result.set("menuTree", menuTree);
        result.set("ids", ids);

        return Result.succ(result);
    }

    //public Result save(Long id) {
    //    return Result.succ();
    //}
    //
    //public Result update(Long id) {
    //    return Result.succ();
    //}
    //

    /**
     * 根据编号删除菜单
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAnyAuthority('sys:menu:delete')")
    public Result delete(@PathVariable Long id) {
        // 1、获取所有子节点编号
        List<Long> ids = menuService.getChildrenIds(id);
        // 2、将菜单及子菜单设置为不可用
        if(menuService.deleteMenusByIds(ids)) {
            return Result.succ("删除成功");
        }
        return Result.fail("删除失败");
    }

    /**
     * 结果列表格式转换
     * @param menus
     * @return
     */
    private List<JSONObject> convert2Jsons(List<Menu> menus) {
        return menus.stream().map(m -> convert2Json(m)).collect(Collectors.toList());
    }

    /**
     * 格式转换
     * @param menu
     * @return
     */
    private JSONObject convert2Json(Menu menu) {
        //Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        JSONObject o = JSONUtil.createObj();
        o.set("id", menu.getId());
        o.set("name", menu.getName());
        o.set("component", menu.getComponent());
        o.set("icon", menu.getIcon());
        o.set("title", menu.getTitle());
        o.set("path", menu.getPath());
        o.set("perms", menu.getPerms());
        o.set("parentId", menu.getParentId());
        o.set("type", menu.getType());
        List<JSONObject> children = menu.getChildren().stream().map(m -> convert2Json(m)).collect(Collectors.toList());
        if(children.size() > 0) {
            o.set("children", children);
        }
        //boolean hasPerms = authorities.stream().anyMatch(auth -> auth.getAuthority().equals(menu.getPerms()));
        //o.set("hasPerms", hasPerms);    // 判断用户是否有该菜单权限
        return o;
    }
}
